package org.nicocube.airain.app.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class FrontServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(FrontServlet.class.getName());

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String thisURL = request.getRequestURI();
		log.info("doGet:"+thisURL);
		
        UserService userService = UserServiceFactory.getUserService();
        
        if (((HttpServletRequest)request).getUserPrincipal() == null || !userService.isUserLoggedIn()) {
    		log.info("redirect to login.");
            response.sendRedirect(userService.createLoginURL(thisURL));
        } else {        	
        	String fn;
        	if (userService.isUserAdmin()) {
        		Pattern pattern = Pattern.compile("(^/$)");
        		
        		Matcher m = pattern.matcher(thisURL);
        		if (m.find()) {
        			fn = "/AirainApp.html";
        		} else {
        			fn = thisURL;
        		}
        		log.info("fn="+fn);
        	} else {
        		log.info("not admin user -> OnConstruction.html");
        		fn="/OnConstruction.html";
        	}
        	
        	String mime = getServletContext().getMimeType(fn);
        	log.info("mime="+mime);
        	response.setContentType(mime);

        	InputStream is = getServletContext().getResourceAsStream(fn);
    	    PrintWriter w = response.getWriter();
    	    
    	    int c;
    	    while ( (c = is.read()) != -1) {
    	    	w.write(c);
    	    }
    	    w.flush();
    	    w.close();
        }
	}
	
}
